import React, { useState, useEffect } from 'react';
import '../MonitoringPanel.css';

interface AlarmStatisticsPanelProps {
  // 可以添加从父组件传入的属性
}

// 告警级别定义
interface AlarmLevel {
  level: string;
  color: string;
  name: string;
}

// 生成模拟的告警统计数据
const generateAlarmData = () => {
  const totalAlarms = Math.floor(Math.random() * 30) + 10; // 10-40条告警
  const alarmLevels: AlarmLevel[] = [
    { level: 'primary', color: '#ff4444', name: '一级警告' },
    { level: 'secondary', color: '#ffaa00', name: '二级警告' },
    { level: 'tertiary', color: '#00f0ff', name: '三级警告' },
    { level: 'quaternary', color: '#74b6ff', name: '四级警告' },
    { level: 'quinary', color: '#44ff44', name: '五级警告' }
  ];
  
  // 随机分配各级别告警数量
  const alarmCounts = alarmLevels.map(() => 0);
  let remaining = totalAlarms;
  
  // 确保每个级别至少有一个告警（除了最后一个）
  for (let i = 0; i < alarmLevels.length - 1 && remaining > 0; i++) {
    const count = Math.floor(Math.random() * remaining) + 1;
    alarmCounts[i] = count;
    remaining -= count;
  }
  
  // 分配剩余的告警给最后一个级别
  if (remaining > 0) {
    alarmCounts[alarmLevels.length - 1] = remaining;
  }
  
  return {
    totalAlarms,
    alarmLevels,
    alarmCounts
  };
};

const AlarmStatisticsPanel: React.FC<AlarmStatisticsPanelProps> = () => {
  const [data, setData] = useState(generateAlarmData());
  const [isAnimating, setIsAnimating] = useState(false);

  // 模拟数据更新
  useEffect(() => {
    const interval = setInterval(() => {
      setIsAnimating(true);
      setTimeout(() => {
        setData(generateAlarmData());
        setIsAnimating(false);
      }, 300);
    }, 18000); // 每18秒更新一次数据

    return () => clearInterval(interval);
  }, []);

  // 计算环形图的圆弧路径
  const calculateArcPath = (index: number, startAngle: number, endAngle: number, radius: number, center: { x: number; y: number }) => {
    const startRad = (startAngle - 90) * (Math.PI / 180);
    const endRad = (endAngle - 90) * (Math.PI / 180);
    
    const startX = center.x + Math.cos(startRad) * radius;
    const startY = center.y + Math.sin(startRad) * radius;
    const endX = center.x + Math.cos(endRad) * radius;
    const endY = center.y + Math.sin(endRad) * radius;
    
    const largeArcFlag = endAngle - startAngle <= 180 ? 0 : 1;
    
    return `M ${center.x} ${center.y} L ${startX} ${startY} A ${radius} ${radius} 0 ${largeArcFlag} 1 ${endX} ${endY} Z`;
  };

  // 绘制环形图
  const renderPieChart = () => {
    const center = { x: 150, y: 80 };
    const outerRadius = 50;
    const innerRadius = 30;
    const total = data.alarmCounts.reduce((sum, count) => sum + count, 0);
    
    if (total === 0) return null;
    
    let currentAngle = 0;
    const arcs: React.ReactNode[] = [];
    const labels: React.ReactNode[] = [];
    
    data.alarmCounts.forEach((count, index) => {
      const angle = (count / total) * 360;
      const startAngle = currentAngle;
      const endAngle = currentAngle + angle;
      
      // 计算扇区中心点
      const midAngle = (startAngle + endAngle) / 2;
      
      // 告警级别标签 - 完整显示所有级别
      labels.push(
        <g key={`alarm-label-${index}`}>
          <circle 
            cx={50 + (index * 50)} 
            cy={140} 
            r="4" 
            fill={data.alarmLevels[index].color}
            stroke="rgba(255,255,255,0.3)"
            strokeWidth="1"
          />
          <text 
            x={60 + (index * 50)} 
            y={144} 
            fill="#ffffff" 
            fontSize="10"
            textAnchor="start"
          >
            {data.alarmLevels[index].name}: {count}
          </text>
        </g>
      );
      
      arcs.push(
        <g key={`arc-${index}`}>
          {/* 发光效果 */}
          <path 
            d={calculateArcPath(index, startAngle, endAngle, outerRadius + 3, center)}
            fill={data.alarmLevels[index].color}
            opacity="0.2"
            filter="blur(3px)"
            className={isAnimating ? 'arc-animation' : ''}
            style={isAnimating ? {
              animation: `arcDraw 0.8s ease-out forwards`,
              animationDelay: `${index * 0.1}s`
            } : {}}
          />
          
          {/* 外环 - 主色 */}
          <path 
            d={calculateArcPath(index, startAngle, endAngle, outerRadius, center)}
            fill={data.alarmLevels[index].color}
            opacity="0.8"
            stroke="rgba(10, 25, 47, 0.5)"
            strokeWidth="1"
            className={isAnimating ? 'arc-animation' : ''}
            style={isAnimating ? {
              animation: `arcDraw 0.8s ease-out forwards`,
              animationDelay: `${index * 0.1}s`
            } : {}}
          />
          
          {/* 外环 - 高亮 */}
          <path 
            d={calculateArcPath(index, startAngle, endAngle, outerRadius, center)}
            fill="none"
            stroke="rgba(255,255,255,0.3)"
            strokeWidth="1"
            className={isAnimating ? 'arc-animation' : ''}
            style={isAnimating ? {
              animation: `arcDraw 0.8s ease-out forwards`,
              animationDelay: `${index * 0.1}s`
            } : {}}
          />
          
          {/* 内环填充 - 增加科技感 */}
          <path 
            d={calculateArcPath(index, startAngle, endAngle, innerRadius, center)}
            fill="rgba(10, 25, 47, 1)"
            stroke="rgba(116, 182, 255, 0.1)"
            strokeWidth="1"
            className={isAnimating ? 'arc-animation' : ''}
            style={isAnimating ? {
              animation: `arcDraw 0.8s ease-out forwards`,
              animationDelay: `${index * 0.1}s`
            } : {}}
          />
          
          {/* 数值标签 */}
          {count > 0 && angle > 25 && (
            <text 
              x={center.x + Math.cos((midAngle - 90) * (Math.PI / 180)) * (outerRadius + innerRadius) / 2}
              y={center.y + Math.sin((midAngle - 90) * (Math.PI / 180)) * (outerRadius + innerRadius) / 2 + 4}
              textAnchor="middle"
              fill="#ffffff"
              fontSize="10"
              fontWeight="bold"
            >
              {count}
            </text>
          )}
        </g>
      );
      
      currentAngle = endAngle;
    });
    
    return (
      <g>
        {/* 背景圆环 */}
        <circle cx={center.x} cy={center.y} r={outerRadius + 5} fill="none" stroke="rgba(116, 182, 255, 0.1)" strokeWidth="1" />
        <circle cx={center.x} cy={center.y} r={outerRadius + 2} fill="none" stroke="rgba(116, 182, 255, 0.15)" strokeWidth="1" />
        <circle cx={center.x} cy={center.y} r={innerRadius - 3} fill="none" stroke="rgba(116, 182, 255, 0.1)" strokeWidth="1" />
        
        {/* 科技感线条 */}
        {[...Array(12)].map((_, i) => {
          const angle = (i * 30 - 90) * (Math.PI / 180);
          const x1 = center.x + Math.cos(angle) * (innerRadius - 2);
          const y1 = center.y + Math.sin(angle) * (innerRadius - 2);
          const x2 = center.x + Math.cos(angle) * (innerRadius - 6);
          const y2 = center.y + Math.sin(angle) * (innerRadius - 6);
          return (
            <line key={`tech-line-${i}`} x1={x1} y1={y1} x2={x2} y2={y2} stroke="rgba(116, 182, 255, 0.3)" strokeWidth="1" />
          );
        })}
        
        {arcs}
        
        {/* 中心装饰 */}
        <circle cx={center.x} cy={center.y} r="3" fill="#74b6ff" opacity="0.8" />
        <circle cx={center.x} cy={center.y} r="5" fill="none" stroke="rgba(116, 182, 255, 0.5)" strokeWidth="1" />
        
        {/* 中心文本 */}
        <text 
          x={center.x}
          y={center.y - 5}
          textAnchor="middle"
          fill="#ffffff"
          fontSize="18"
          fontWeight="bold"
          className={isAnimating ? 'data-update' : ''}
        >
          {data.totalAlarms}
        </text>
        <text 
          x={center.x}
          y={center.y + 15}
          textAnchor="middle"
          fill="#74b6ff"
          fontSize="10"
          fontWeight="500"
        >
          告警总数
        </text>
        
        {/* 告警级别标签 */}
        <g transform="translate(0, 130)">
          <rect x="0" y="0" width="300" height="20" fill="rgba(10, 25, 47, 0.6)" rx="3" ry="3" />
          <g transform="translate(30, 0)">
            {labels}
          </g>
        </g>
      </g>
    );
  };

  return (
    <div className={`monitoring-panel ${isAnimating ? 'data-update' : ''}`}>
      <div className="panel-header">
        <h3 className="panel-title">
          告警统计
          <span style={{ fontSize: '12px', fontWeight: 'normal', marginLeft: '8px', color: '#a0aec0' }}>
           
          </span>
        </h3>
        {/* 添加内联样式的装饰条 */}
        <div style={{ display: 'flex', gap: '4px' }}>
          {[...Array(4)].map((_, i) => (
            <div 
              key={i} 
              style={{
                width: '4px',
                height: '14px',
                background: 'linear-gradient(180deg, #74b6ff 0%, #00f0ff 100%)',
                borderRadius: '2px'
              }}
            />
          ))}
        </div>
      </div>
      
      <div className="chart-container">
        <svg width="100%" height="100%" viewBox="0 0 300 180">
          {renderPieChart()}
        </svg>
      </div>
    </div>
  );
};

export default AlarmStatisticsPanel;